import pickle, base64
from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
        合并购物车数据
        :param request: 借用以获取cookie购物车数据
        :param user: 想要获取redis hash和set
        :param response: 借用过来删除cookie
        :return: None
        """
    # 获取cookie购物车数据
    cart_str = request.COOKIES.get('cart')
    # 判断有没有cookie购物车数据,如果没有直接return
    if cart_str is None:
        return
        # 把cookie字符串转换成cart_dict
    cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
    # 创建redis连接对象
    redis_conn = get_redis_connection('cart')
    # 创建管道
    pl = redis_conn.pipline()

    # 遍历cookie购物车大字典
    for sku_id in cart_dict:
        pl.hset('cart_%s' % user.id, sku_id, cart_dict[sku_id]['count'])
        # 如果cookie购物车当前sku_id是选中
        if cart_dict[sku_id]['selected']:
            pl.sadd('selected_%s' % user.id, sku_id)

    # 执行管道
    pl.execute()

    #清空cookie购物车数据
    response.delete_cookie('cart')